package com.xuecheng.manager_course.service;

import com.xuecheng.framework.domain.course.CourseBase;
import com.xuecheng.framework.domain.course.CourseMarket;
import com.xuecheng.framework.domain.course.response.CourseCode;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manager_course.dao.CourseBaseRepository;
import com.xuecheng.manager_course.dao.CourseMarketRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
public class CourseMarketService {
    @Autowired
    private CourseMarketRepository courseMarketRepository;
    @Autowired
    private CourseBaseRepository courseBaseRepository;

    public CourseMarket findById(String courseId) {
        Optional<CourseMarket> byId = courseMarketRepository.findById(courseId);
        if (!byId.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        return byId.get();
    }
    @Transactional
    public ResponseResult update(String id, CourseMarket courseMarket) {
        Optional<CourseBase> byId = courseBaseRepository.findById(id);
        if (!byId.isPresent()){
            ExceptionCast.cast(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        Optional<CourseMarket> courseMarketOptional = courseMarketRepository.findById(id);
        CourseMarket courseMarketNew=null;
        if (!courseMarketOptional.isPresent()){
           courseMarketNew=new CourseMarket();
        }else {
            courseMarketNew=courseMarketOptional.get();
        }
        courseMarketNew.setId(courseMarket.getId());
        courseMarketNew.setCharge(courseMarket.getCharge());
        courseMarketNew.setValid(courseMarket.getValid());
       if(StringUtils.isEmpty(courseMarket.getStartTime().toString())){
           courseMarket.setStartTime(new Date());
       }
        courseMarketNew.setEndTime(courseMarket.getEndTime());
        if(StringUtils.isNotEmpty(courseMarketNew.getPrice().toString())){
            courseMarketNew.setPrice_old(courseMarketNew.getPrice());
        }
        courseMarketNew.setPrice(courseMarket.getPrice());
        courseMarketNew.setQq(courseMarket.getQq());
        courseMarketRepository.save(courseMarketNew);

        return new ResponseResult(CommonCode.SUCCESS);
    }
}
